﻿using MMOArpgServer.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MMOArpgServer.Pool
{
  public  class DBConnectPool
    {
        private static  DBConnectPool _Instance;
        private static readonly object lockObj = new object();
        private const int MAX_CONNECT_COUNT=1024;
        private Queue<DBConnect> _Pool = new Queue<DBConnect>();
        private List<DBConnect> _UseConnects = new List<DBConnect>();

        public static DBConnectPool GetInstance() {
            lock (lockObj) {
                if (_Instance==null) {
                    _Instance = new DBConnectPool();
                }
            }
            return _Instance;
        }
        private DBConnectPool() {
            for (int i =0;i<MAX_CONNECT_COUNT;i++) {
               _Pool.Enqueue(new DBConnect());
            }
        }
        public DBConnect GetConnect() {
            DBConnect connect = _Pool.Dequeue();
            _UseConnects.Add(connect);
            return connect;
        }
        public void CloseConnect(DBConnect connect) {
            _Pool.Enqueue(connect);
            _UseConnects.Remove(connect);
        }
        public void Close() {

            foreach (DBConnect temp in _UseConnects) {
                temp.Close();
            }
        }        
    }
}
